<template>
  <div>
    <el-form label-width="100px">
      <el-form-item label="SPU名称">
        <el-input
          placeholder="请输入spu名称"
          v-model="spuParams.spuName"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU品牌">
        <el-select v-model="spuParams.tmId">
          <el-option
            v-for="(item, index) in AllTrademarkMark"
            :label="item.tmName"
            :key="index"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          placeholder="请输入SPU描述"
          type="textarea"
          v-model="spuParams.description"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU照片">
        <el-upload
          v-model:file-list="imgList"
          action="http://sph-api.atguigu.cn/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :before-upload="handleBeforeUpload"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img
            w-full
            :src="dialogImageUrl"
            alt="Preview Image"
            style="width: 100%; height: 100%"
          />
        </el-dialog>
      </el-form-item>
      <el-form-item label="SPU销售属性">
        <el-select
          v-model="saleAttrIdAndValueName"
          style="margin: 10px 10px"
          :placeholder="
            unSelectSaleAttr.length
              ? `还未选择${unSelectSaleAttr.length}个销售属性`
              : `无`
          "
        >
          <el-option
            :value="`${item.id}:${item.name}`"
            v-for="(item, index) in unSelectSaleAttr"
            :key="item.id"
            :label="item.name"
          ></el-option>
        </el-select>
        <el-button
          :disabled="saleAttrIdAndValueName ? false : true"
          icon="Plus"
          type="primary"
          size="default"
          @click="addSaleAttr"
        >
          添加销售属性
        </el-button>
        <el-table border :data="SaleAttrList">
          <el-table-column
            label="序号"
            fixed="left"
            width="100"
            align="center"
            prop="id"
          ></el-table-column>
          <el-table-column
            label="属性名"
            width="100"
            prop="saleAttrName"
          ></el-table-column>
          <el-table-column label="属性值">
            <template #="{ row, index }">
              <el-tag
                @close="row.spuSaleAttrValueList.splice(index, 1)"
                closable
                type="warning"
                v-for="(item, index) in row.spuSaleAttrValueList"
                :key="index"
                style="margin: 0px 5px"
              >
                {{ item.saleAttrValueName }}
              </el-tag>
              <el-input
                v-if="row.flag == true"
                placeholder="请输入属性值"
                size="small"
                style="width: 100px"
                v-model="row.saleAttrValue"
                @blur="toLook(row)"
              ></el-input>
              <el-button
                v-else
                @click="toEdit(row)"
                type="warning"
                size="small"
                icon="Plus"
              ></el-button>
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            fixed="right"
            width="100"
            align="center"
          >
            <template #="{ row, index }">
              <el-button
                type="primary"
                size="small"
                icon="Delete"
                @click="SaleAttrList.splice(index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveSubmit">确定</el-button>
        <el-button type="info" @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup lang="ts">
import {
  reqAllTrademark,
  reqSpuImageList,
  reqSpuSaleAttrList,
  reqAllSaleAttr,
  reqAddUpdateSpuu,
} from '@/api/product/spu/spu'
import type {
  ASaleAttr,
  AllSaleAttrRes,
  AllTrademark,
  SaleAttr,
  SaleAttrValue,
  SpuData,
  SpuImage,
  SpuImageRes,
  SpuSaleAttrRes,
  Trademark,
} from '@/api/product/spu/type'
import { ElMessage } from 'element-plus'

import { computed, ref } from 'vue'

let $emit = defineEmits(['changeScene'])
//取消保存 显示spu列表页面
const cancel = () => {
  SaleAttrList.value = []
  imgList.value = []
  saleAttrIdAndValueName.value = ''
  spuParams.value = {
    spuName: '',
    description: '',
    category3Id: '',
    spuImageList: [],
    spuSaleAttrList: [],
    tmId: '',
  }
  $emit('changeScene', 0)
}
//存储已有spu的全部数据
let AllTrademarkMark = ref<Trademark[]>([])
let imgList = ref<SpuImage[]>([])
let AllsaleAttrList = ref<ASaleAttr[]>([])
let SaleAttrList = ref<SaleAttr[]>([])
let spuParams = ref<SpuData>({
  spuName: '',
  description: '',
  category3Id: '',
  spuImageList: [],
  spuSaleAttrList: [],
  tmId: '',
})
//收集还未选择的销售属性和id
let saleAttrIdAndValueName = ref<string>('')
//获取spu的全部信息
const initHasSpuData = async (spuRow: SpuData) => {
  // //获取spu的全部已有的销售属性
  // let result: SpuSaleAttrRes = await reqSpuSaleAttrList(spuRow.id as number)
  // //获取spu全部的售卖商品的图片数据
  // let result1: SpuImageRes = await reqSpuImageList(spuRow.id as number)
  // //获取全部品牌的数据
  // let result2: AllTrademark = await reqAllTrademark()
  // //获取整个项目全部的销售属性
  // let result3: AllSaleAttrRes = await reqAllSaleAttr()

  let [result, result1, result2, result3] = await Promise.all([
    //获取spu的全部已有的销售属性
    reqSpuSaleAttrList(spuRow.id as number),
    //获取spu全部的售卖商品的图片数据
    reqSpuImageList(spuRow.id as number),
    //获取全部品牌的数据
    reqAllTrademark(),
    //获取整个项目全部的销售属性
    reqAllSaleAttr(),
  ])
  AllTrademarkMark.value = result2.data
  imgList.value = result1.data.map((item) => {
    return {
      name: item.imgName,
      url: item.imgUrl,
    }
  })
  AllsaleAttrList.value = result3.data
  SaleAttrList.value = result.data
  spuParams.value = spuRow
}
//添加一个spu
const initAddSpu = async (c3Id: string | number) => {
  spuParams.value.category3Id = c3Id
  //获取全部品牌的数据
  let result2: AllTrademark = await reqAllTrademark()
  //获取整个项目全部的销售属性
  let result3: AllSaleAttrRes = await reqAllSaleAttr()
  AllTrademarkMark.value = result2.data
  AllsaleAttrList.value = result3.data
}
//对话框的图片预览显示与因此
let dialogVisible = ref<boolean>(false)
//对话框图片的地址
let dialogImageUrl = ref<string>('')
//文件列表移除文件时的钩子
const handleRemove = (file: any) => {
  imgList.value = imgList.value.filter((item) => item.url !== file.url)
}
//上传文件之前的钩子，参数为上传的文件，
const handleBeforeUpload = (file: any) => {
  //限制上传图片的格式
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  if (!isJPG && !isPNG) {
    ElMessage({
      type: 'error',
      message: '上传图片只能是jpg或png格式!',
    })
    return false
  }
  //限制上传图片的大小
  if (file.size / 1024 / 1024 < 3) {
    return true
  } else {
    ElMessage({
      type: 'error',
      message: '上传图片大小不能超过3M!',
    })
    return false
  }
}
//点击文件列表中已上传的文件时的钩子
const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}
//计算还没有的销售属性
let unSelectSaleAttr = computed(() => {
  let unSelecArr = AllsaleAttrList.value.filter((item) => {
    return SaleAttrList.value.every((item1) => {
      return item1.saleAttrName != item.name
    })
  })
  return unSelecArr
})
//添加销售属性
const addSaleAttr = () => {
  const [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':')
  let newSaleAttr: SaleAttr = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  }
  SaleAttrList.value.push(newSaleAttr)
  saleAttrIdAndValueName.value = ''
}
//编辑销售属性
const toEdit = (row: SaleAttr) => {
  row.flag = true
  row.saleAttrValue = ''
}
//保存销售属性
const toLook = (row: SaleAttr) => {
  const { baseSaleAttrId, saleAttrValue } = row
  let newSaleAttr: SaleAttrValue = {
    baseSaleAttrId: baseSaleAttrId as number,
    saleAttrValueName: saleAttrValue as string,
  }
  if (saleAttrValue?.trim() == '') {
    ElMessage({
      type: 'error',
      message: '销售属性值不能为空!',
    })
    return
  }
  //判断属性值是否在数组中存在
  if (
    row.spuSaleAttrValueList.some(
      (item) => item.saleAttrValueName == saleAttrValue,
    )
  ) {
    ElMessage({
      type: 'error',
      message: '销售属性值已存在!',
    })
    return
  }
  row.spuSaleAttrValueList.push(newSaleAttr)
  row.saleAttrValue = ''
  row.flag = false
}

//保存提交
const saveSubmit = async () => {
  //整理参数
  //照片墙数据
  spuParams.value.spuImageList = imgList.value.map((item: any) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url,
    }
  })
  //整理销售属性的数据
  spuParams.value.spuSaleAttrList = SaleAttrList.value
  //发送请求
  let req = await reqAddUpdateSpuu(spuParams.value)
  if (req.code == 200) {
    ElMessage({
      type: 'success',
      message: '保存成功!',
    })
    cancel()
  } else {
    ElMessage({
      type: 'error',
      message: req.data,
    })
  }
}

//对外暴露
defineExpose({
  initHasSpuData,
  initAddSpu,
})
</script>
<style scoped lang="scss"></style>
